Ext.ns('app.crud.articles');

app.crud.articles.canEdit = false;
app.crud.articles.canPublish = false;
app.crud.articles.canDelete = false;
app.crud.articles.topics = false;

Ext.define('app.crud.articles.Model', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'id', type:'integer'},
        {name:'parent_id' , type:'integer'},
        {name:'code' , type:'string'},
        {name:'title', type:'string'},
        {name:'allow_comments', type:'boolean'},
        {name:'allow_votes', type:'boolean'},
        {name:'published' , type:'boolean'},
        {name:'topic_id', type:'integer'},
        {name:'date_created' , type:'date' ,dateFormat:"Y-m-d H:i:s"},
        {name:'date_updated' , type:'date' ,dateFormat:"Y-m-d H:i:s"},
        {name:'user' , type:'string'},
        {name:'updater' , type:'string'},
        {name:'last_version' , type:'integer'},
        {name:'published_version' , type:'integer'}
    ]
});

Ext.define('app.crud.articles.Window',{
	   extend:'app.contentWindow',
	   textPanel:null,
	   blocksPanel:null,
	   linkComponents:[],

	   constructor: function(config) {		
			config = Ext.apply({
		        title: 'Articles :: Edit Item',
		        width: 800,
		        height:640,
		        objectName:'articles',
		        controllerUrl:app.root
		    }, config);		
			
			this.callParent(arguments);

			this.textPanel = Ext.create('app.medialib.HtmlPanel',{
		    	title:'Text',
		    	editorName:'text'
			});
					
			this.relatedPanel = Ext.create('app.relatedGridPanel',{
				title:'Related Topics',
				fieldName:'related_topics',
				listeners:{
					'addItemCall':{
						fn:function(){
							var win = Ext.create('app.SelectWindow',{
								width:700,
								height:600,
								title:'Select Topic',
								dataPanel:Ext.create('app.topics.Panel',{
									canEdit:false,
									canDelete:false,
									selectMode:true
								}),
								listeners:{
									'itemSelected':{
										fn:function(record){
											this.relatedPanel.addRecord(record);
										},
										scope:this
									}
									
								}
							}).show();	
						},
						scope:this
					}
				}
			});
			
			this.registerLink(this.relatedPanel);
			
			this.contentTabs.getComponent(0).add([
				{
					fieldLabel:"parent_id",
					name:"parent_id",
					xtype:"hidden",
					value:0
				},{
					allowBlank: false,
					fieldLabel:"Page Code",
					name:"code",
					vtype:"alphanum",
					xtype:"textfield",
					enableKeyEvents:true,
					validateOnBlur :false,
					listeners:{
						'keyup' : {
							 fn: this.checkCode,
							 scope:this,
							 buffer:400
						}
					}
				},{
					allowBlank: false,
					fieldLabel:"Title",
					name:"title",
					xtype:"textfield"
				},{
					displayField:"title",
					queryMode:"local",
					triggerAction:"all",
					valueField:"id",
					allowBlank: false,
					fieldLabel:"Main Topic",
					name:"main_topic",
					xtype:"combo",
					store:Ext.create('Ext.data.Store',{									
						model:app.comboModel,
						data:Ext.clone(app.crud.articles.topics),
						sorters:[ {
						    field: 'title',
						    direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
						}]
					})
				},{
					name:'allow_comments',
					xtype:'checkbox',
					inputValue:1,
					fieldLabel:'Allow Comments'
				},{
					name:'allow_votes',
					xtype:'checkbox',
					inputValue:1,
					fieldLabel:'Allow Votes'
				},{
					fieldLabel:"META KEYWORDS",
					name:"meta_keywords",
					width: 250,
					xtype:"textarea"
				},{
					fieldLabel:"META DESCRIPTION",
					name:"meta_description",
					width: 250,
					xtype:"textarea"
				},{
					name:'brief',
					width: 250,
					xtype:"textarea",
					fieldLabel:'Brief'
				}
			 ]);
				
			this.contentTabs.add([this.textPanel,this.relatedPanel]);
			
			this.on('dataLoaded' , function(result){
	 			    if(this.isFixed){
	 			    	this.editForm.getForm().findField('code').setReadOnly(true);
	 			    	this.unpublishBtn.hide();
	 			    	this.deleteBtn.hide();
	 			    }else{
	 			    	this.editForm.getForm().findField('code').setReadOnly(false);
	 			    	this.deleteBtn.show();
	 			    }  
			}, this);
			
	   },
	   checkCode: function(field  , event)
	   {
			 var val = field.getValue();
			 
			 Ext.Ajax.request({
			 		url: this.controllerUrl + "checkcode",
			 		method: 'post',
			 		params:{
			 			'id':this.editForm.getForm().findField('id').getValue(),
			 			'code':val
			 		},
			         success: function(response, request) {
			 			response =  Ext.JSON.decode(response.responseText);
			 			if(response.success){
			 				field.setValue(response.data.code);
			 				field.unsetActiveError();
			 			}else{
			 				field.markInvalid(response.msg);
			 				field.setActiveError(response.msg);
			 			}	
			       },
			       failure:function() {
			       	Ext.Msg.alert('Message', "Server is not responding");   	
			       }
			 	});
			  
		}
});



Ext.define('app.crud.articles.Main',{
	  extend:'Ext.panel.Panel',
	  /**
	    * @property {Ext.grid.Panel}
	    */
	   dataGrid:null,
	   /**
	    * @property {Ext.data.Store}
	    */
	   dataStore:null,
	   /**
	    * @property {searchBar}
	    */
	   searchField: null,
	   /**
	    * @property {Ext.Button}
	    */
	   addItemBtn: null,
	   /**
	    * @property {Ext.form.field.ComboBox}
	    */
	   topicFilter:null,
	   /**
	    * @property {Ext.data.Store}
	    */
	   topicFilterStore:null,
	   
	   constructor: function(config) {
			
			config = Ext.apply({
				layout:'fit'
		    }, config);		
			
			this.callParent(arguments);
	   },
	   
	   initComponent:function(){
			
			this.dataStore = Ext.create('Ext.data.Store', {
			    model: 'app.crud.articles.Model',
			    proxy: {
			        type: 'ajax',
			    	url:app.root +  'list',
			        reader: {
			            type: 'json',
			            root: 'data',
			            totalProperty: 'count',
			            idProperty: 'id'
			        },
			        startParam:'pager[start]',
			        limitParam:'pager[limit]',
			        sortParam:'pager[sort]',
			        directionParam:'pager[dir]',
				    simpleSortMode: true
			    },
			    pageSize: 50,
		        remoteSort: true,
			    autoLoad: true,
			    sorters: [{
	                  property : 'date_updated',
	                  direction: 'DESC'
	            },
	            {
	                  property : 'date_created',
	                  direction: 'DESC'
	            }]
			});
			
		    this.searchField = Ext.create('SearchPanel',{store:this.dataStore,local:false});
		    
		    this.topicFilterStore = Ext.create('Ext.data.Store',{									
				model:app.comboModel,
				data:[],
				sorters:[ {
				    field: 'title',
				    direction: 'ASC'
				}]
			});
		    
		    this.topicFilter = Ext.create('Ext.form.field.ComboBox',{
		    	displayField:"title",
				queryMode:"local",
				triggerAction:"all",
				valueField:"id",
				value:'',
				emptyText:'All',
				store:this.topicFilterStore,
				listeners:{
					select:{
						fn:function(cmp){
							 var value = cmp.getValue();
							 if(value == 0){
								 value = '';
							 }
							 this.dataStore.proxy.extraParams['filter[main_topic]'] = value;
							 this.dataStore.load();
						},
						scope:this
					}
				}
		    });
	
			this.addItemBtn = new Ext.Button({
				 text:'Add Item',
				 hidden:(!app.crud.articles.canEdit )
			});
			
			this.addItemBtn.on('click' , function(){
				 this.showPageEdit(0);
			} , this);
			
			
			this.dataGrid = Ext.create('Ext.grid.Panel',{
					store: this.dataStore,
				 	viewConfig:{
				 		stripeRows:false
				 	},
		            frame: false,
		            loadMask:true,
				    columnLines: true,
				    autoscroll:true,
				    tbar:[
				            'Topic: ',this.topicFilter,'-', this.addItemBtn,'->',this.searchField,
				    ],
				    columns: [
							{
								id: 'published',
							    sortable: true,
							    text: 'Status',
							    dataIndex: 'published',
							    width:50,
							    align:'center',
							    renderer:app.publishRenderer 
							}, {
								text:'Versions (Published / Last)',
								dataIndex:'id',
								align:'center',
								width:150,
								renderer:app.versionRenderer
				             }, {
					            sortable: true,
					            text: 'Page Code',
					            dataIndex: 'code',
					            width:80
					        },{
								id: 'title',
							    sortable: true,
							    text: 'Headline',
							    dataIndex: 'title',
							    flex:1
							},{
					        	text:'Created by',
					        	dataIndex:'date',
					        	sortable: true,
					        	width:210,
					        	renderer:app.creatorRenderer
					          },{
					        	text:'Updated By',
					        	dataIndex:'date_updated',
					        	sortable: true,
						        width:210,
						        renderer:app.updaterRenderer
					          }
				    ],
					bbar: Ext.create('Ext.PagingToolbar', {
			            store: this.dataStore,
			            displayInfo: true,
			            displayMsg: 'Displaying records {0} - {1} of {2}',
			            emptyMsg: "No records to display"
			        }),
					listeners : {
				    	'itemdblclick':{
				    		fn:function(view , record , number , event , options){
				    			 this.showPageEdit(record.get('id'));
				    		},
				    		scope:this
				    	}
					}
			});
			
			this.items = [this.dataGrid];
			this.callParent(arguments);
	   },
	   showPageEdit: function(id){
			var win = Ext.create('app.crud.articles.Window', {
				dataItemId:id,
				canDelete:app.crud.articles.canDelete,
				canEdit:app.crud.articles.canEdit,
				canPublish:app.crud.articles.canPublish
			});
			
			win.on('dataSaved' , function(){
				this.dataStore.load();
			}, this);		
			
			win.show();		
			if(id){
				win.loadData(id , false);
			}	
		}
});


Ext.onReady(function(){ 
	
	Ext.QuickTips.init();
	
	app.crud.articles.canEdit = canEdit;
	app.crud.articles.canPublish = canPublish;
	app.crud.articles.canDelete = canDelete;	
	var appMain = Ext.create('app.crud.articles.Main',{title:'Articles :: Home'});
			
	Ext.Ajax.request({
 		url: app.createUrl([app.admin , 'topics' , 'combolist'] , app.delimeter),
 		method: 'post',
        success: function(response, request) {
 			response =  Ext.JSON.decode(response.responseText);
 			if(response.success){
 				app.crud.articles.topics = response.data;
 				var list = Ext.Array.merge([{id:'',title:'All'}] , Ext.clone(app.crud.articles.topics));
 				appMain.topicFilterStore.loadData(list);
 				app.content.add(appMain);
 			}else{
 				Ext.Msg.alert('Message', "Cant load topic list");  
 			}
       },
       failure:function() {
       	Ext.Msg.alert('Message', "Server is not responding");   	
       }
 	});
	
});